<template>
  <div
    class="chat-pc layout-bg chat-pc-new"
    :class="classObj"
    v-loading="loading"
    :style="{
      '--el-color-primary': applicationDetail?.custom_theme?.theme_color,
      '--el-color-primary-light-9': hexToRgba(applicationDetail?.custom_theme?.theme_color, 0.1)
    }"
  >
    <div class="flex-row">
      <div class="right">
        <div class="right-height chat-width">

          <div class="right-height chat-width" style="width: 800px;">
            <DiyContractReview 
              :app-id="applicationDetail?.id" 
              :chat-id="currentChatId" 
              :applicationDetails="applicationDetail"
            >
              <template #one>
                <AiChatDiy
                  v-if="isShowChat"
                  ref="AiChatRef"
                  v-model:applicationDetails="applicationDetail"
                  :available="applicationAvailable"
                  type="ai-chat"
                  :appId="applicationDetail?.id"
                  :record="currentRecordList"
                  :chatId="currentChatId"
                  @refresh="refresh"
                  @scroll="handleScroll"
                ></AiChatDiy>
              </template>
            </DiyContractReview>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue'
import useStore from '@/stores'
import useResize from '@/layout/hooks/useResize'
import { hexToRgba } from '@/utils/theme'
import { t } from '@/locales'
import defImg from '@/assets/agent/def_agent.svg'
import DiyContractReview from '@/views/diy/chat/components/DiyContractReview.vue'
import bus from '@/bus'

useResize()

const { user, log, common } = useStore()

const hasCustomAgent = computed(() => applicationDetail.value.renderingType !== '')

const isCollapse = ref(true)

const classObj = computed(() => {
  return {
    mobile: common.isMobile(),
    hideLeft: !isCollapse.value,
  }
})

const newObj = {
  id: 'new',
  abstract: t('chat.createChat')
}
const props = defineProps<{
  application_profile: any
  applicationAvailable: boolean
}>()
const emit = defineEmits(['update:application_profile']);
const AiChatRef = ref()
const loading = ref(false)
const left_loading = ref(false)
const isShowChat = ref(true)

const applicationDetail = computed({
  get: () => {
    return {
      ...props.application_profile,
      avatar: localStorage.getItem('avatar') || defImg,
      renderingType: localStorage.getItem('renderingType') || ''
    }
  },
  set: (v) => {
    emit('update:application_profile', v);
  }
})

const chatLogData = ref<any[]>([])

const paginationConfig = ref({
  current_page: 1,
  page_size: 20,
  total: 0
})

const currentRecordList = ref<any>([])
const currentChatId = ref('new') // 当前历史记录Id 默认为'new'
const currentChatName = ref(t('chat.createChat'))

function handleScroll(event: any) {
  if (
    currentChatId.value !== 'new' &&
    event.scrollTop === 0 &&
    paginationConfig.value.total > currentRecordList.value.length
  ) {
    const history_height = event.dialogScrollbar.offsetHeight
    paginationConfig.value.current_page += 1
    getChatRecord().then(() => {
      event.scrollDiv.setScrollTop(event.dialogScrollbar.offsetHeight - history_height)
    })
  }
}

function newChat() {
  if (!chatLogData.value.some((v) => v.id === 'new')) {
    paginationConfig.value.current_page = 1
    paginationConfig.value.total = 0
    currentRecordList.value = []
    chatLogData.value.unshift(newObj)
  } else {
    paginationConfig.value.current_page = 1
    paginationConfig.value.total = 0
    currentRecordList.value = []
  }
  currentChatId.value = 'new'
  currentChatName.value = t('chat.createChat')
  if (common.isMobile()) {
    isCollapse.value = false
  }
}
function getChatLog(id: string, refresh?: boolean) {
  const page = {
    current_page: 1,
    page_size: 20
  }

  log.asyncGetChatLogClient(id, page, left_loading).then((res: any) => {
    chatLogData.value = res.data.records
    if (refresh) {
      currentChatName.value = chatLogData.value?.[0]?.abstract
    } else {
      newChat()
      paginationConfig.value.current_page = 1
      paginationConfig.value.total = 0
      currentRecordList.value = []
      currentChatId.value = chatLogData.value?.[0]?.id || 'new'
      currentChatName.value = chatLogData.value?.[0]?.abstract || t('chat.createChat')
      if (currentChatId.value !== 'new') {
        getChatRecord()
      }
    }
  })
}

function getChatRecord() {
  return log
    .asyncChatRecordLog(
      applicationDetail.value.id,
      currentChatId.value,
      paginationConfig.value,
      loading,
      false
    )
    .then((res: any) => {
      paginationConfig.value.total = res.data.total
      const list = res.data.records
      list.map((v: any) => {
        v['write_ed'] = true
        v['record_id'] = v.id
      })
      currentRecordList.value = [...list, ...currentRecordList.value].sort((a, b) =>
        a.create_time.localeCompare(b.create_time)
      )
      if (paginationConfig.value.current_page === 1) {
        nextTick(() => {
          // 将滚动条滚动到最下面
          AiChatRef.value.setScrollBottom()
        })
      }
    })
}

function refresh(id: string) {
  getChatLog(applicationDetail.value.id, true)
  currentChatId.value = id
}

/**
 *初始化历史对话记录
 */
const init = () => {
  if (
    (applicationDetail.value.show_history || !user.isEnterprise()) &&
    props.applicationAvailable
  ) {
    getChatLog(applicationDetail.value.id)
  }
}
onMounted(() => {
  init()

  bus.on('hidden-chat-message', () => {
    isShowChat.value = false
  })

  bus.on('show-chat-message', () => {
    isShowChat.value = true
  })

})
</script>
<style lang="scss">
@import "./index.scss";
</style>
